package Scuttlebutt;

import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import glue.ftp.*;
import javax.swing.event.*;
import java.net.URL;
import java.net.URLConnection;

public class URLPopupMenu extends JPopupMenu 
{

	
	class ConfirmThread implements Runnable{	
		Scuttlebutt parent = null;
		public ConfirmThread(Scuttlebutt parent){
			this.parent = parent;
			
		}
		
		public void run(){
			StringBuilder buffer = new StringBuilder();
			URLNode o = (URLNode)parent.getProject().getTree().getLastSelectedPathComponent();
			try{
				URL url = new URL(o.getURL());
				URLConnection c = url.openConnection();
				String type = c.getContentType();
//				System.out.println(type);
//				Object content = c.getContent();
//				System.out.println(content);

				InputStream s = url.openStream();
		 		int val = 0;
			    
		 		while( (val = s.read()) != -1){
			 		buffer.append((char)val);
		 		}
		 		s.close();
//		 		System.out.println(buffer);
				
				
			}catch(java.net.MalformedURLException m){
//				System.err.println("MalformedURLException:" + m);
		        JOptionPane.showMessageDialog(null, m, "Error", JOptionPane.ERROR_MESSAGE);
		        return;
			}catch(IOException ioe){
//				System.err.println("IOException:" + ioe);
		        JOptionPane.showMessageDialog(null, ioe, "Error", JOptionPane.ERROR_MESSAGE);
		        return;
			}
			
			JOptionPane.showMessageDialog(null, new String("URL \"" + o.getURL() + "\" found."), "Success", JOptionPane.PLAIN_MESSAGE);
		}
	}	
	
	public class ConfirmURL extends JMenuItem implements ActionListener{
		Scuttlebutt parent = null;
		public ConfirmURL(Scuttlebutt parent){
			super("Confirm");
			addActionListener(this);
			this.parent = parent;
		}
		
		public void actionPerformed(ActionEvent a0)
		{
			new Thread(new ConfirmThread(parent)).start();
		}
	}
	
	
	
	public class EventDeleteURL extends JMenuItem implements ActionListener{
		Scuttlebutt parent = null;
		public EventDeleteURL(Scuttlebutt parent){
			super("Delete");
			addActionListener(this);
			this.parent = parent;
		}
		
		public void actionPerformed(ActionEvent a0)
		{
			SortableNode o = (SortableNode)parent.getProject().getTree().getLastSelectedPathComponent();
			o.removeFromParent();
			parent.updateTree();
		}
	}
	
	public URLPopupMenu(Scuttlebutt parent)
	{
		add(new ConfirmURL(parent));
		add(new EventDeleteURL(parent));
	}	
}

